package com.qianji.aopconfig;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.annotation.*;

import org.slf4j.Logger;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import java.util.Arrays;

/**
 * Created by 阳家桂 on 2021/3/26 17:13
 */

@Aspect
@Component
public class LogAspect {

    private final static Logger log = org.slf4j.LoggerFactory.getLogger(LogAspect.class);

    /**
     * 定义切入点函数
     */
    @Pointcut("execution(* com.qianji.service.impl.*ServiceImpl.*(..))")
    public void Log(){}

    /**
     * 前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
    @Before("Log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + JSONUtil.toJsonStr(joinPoint.getArgs()));//入参

    }

/*    @AfterReturning(returning = "ret",pointcut = "Log()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
    }*/
}
